# -*- coding: utf-8 -*-
# 多进程

import os,time,random

from multiprocessing import Process,Queue
from multiprocessing import Pool
import io
import subprocess
import sys
import functools
import os,time,random

# sys.stdout = io.TextIOWrapper(sys.stdout.buffer,encoding='utf-8')

##### Only works on Unix/Linux/Mac
# print('Process (%s) start...'  % os.getpid())
# pid = os.fork()
# if pid == 0:
# 	print('I am child process (%s) and my parent is %s.' % (os.getpid(), os.getppid()))
# else:
# 	print('I (%s) just created a child process (%s).' % (os.getpid(), pid))

# 
##### multiprocessing模块就是跨平台版本的多进程模块
# 

##### 子进程要执行的代码
# def run_proc(name):
# 	print('Run child process %s (%s)...' % (name, os.getpid()))

# if __name__ =='__main__':
# 	print('Parent process %s.' % os.getpid())
# 	p = Process(target=run_proc,args=('test',))
# 	print('Child process will start.')
# 	p.start() # 启动进程，这样创建进程比fork()还要简单
# 	p.join() # 等待紫禁城结束后再继续往下运行，通常用于进程间的同步
# 	print('Child process end.')

##### Pool 进程池 批量创建子进程
# def long_time_task(name):
# 	print('Run task %s (%s)...' % (name,os.getpid()))
# 	start = time.time()
# 	time.sleep(random.random() * 3)
# 	end = time.time()
# 	print('Task %s runs %0.2f seconds.' % (name,(end -start)))

# if __name__=='__main__':
# 	print('Parent process %s.' % os.getpid())
# 	p = Pool(4)  # pool 的默认大小是CPU的核数
# 	for i in range(5):
# 		p.apply_async(long_time_task,args=(i,))
# 	print('Waiting for all subprocesses donw...')
# 	p.close() # 调用close()之后就不能继续添加新的Process
# 	p.join() # 调用join前面必须调用close()
# 	print('All subprocesses done.')

##### 子进程
# print('$ nslookup www.python.org')
# r = subprocess.call(['nslookup','www.pythopn.org'])
# print('Exit code:',r)

##### 子进程使用communicate

# print('$ nslookup')
# p = subprocess.Popen(['nslookup'],stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
# output,err = p.communicate(b'set q=mx\npython.org\nexit\n')
# print(output.decode('gbk'))
# print('Exit code:',p.returncode)


##### 子进程交换数据，通过Queue，一个往Queue写数据，一个往Queue读数据

# 写数据进程执行的代码
def write(q):
	print('Process to write: %s' % os.getpid())
	for value in ['A','B','C']:
		print('Put %s to queue...' % value)
		q.put(value)
		time.sleep(random.random() * 2)

# 读数据进程执行的代码
def read(q):
	print('Process to read: %s' % os.getpid())
	while not q.empty():
		value = q.get(True)
		print('Get %s from queue' % value)

if __name__=='__main__':
	# 父进程创建Queue，并传给各个子进程
	q = Queue()
	pw = Process(target=write,args=(q,))
	pr = Process(target=read,args=(q,))
	# 启动子进程pw,写入
	pw.start()
	# 启动子进程pr 读取
	pr.start()
	# 等待pw结束
	pw.join()
	# pr进程里面是死循环，无法等待其结束，只能强行终止
	pr.terminate()


###### 总结

# 在Unix/Linux下，可以使用fork()调用实现多进程。

# 要实现跨平台的多进程，可以使用multiprocessing模块。

# 进程间通信是通过Queue、Pipes等实现的。